/***********************************************************************************************************************
*                                                                                                                      *
* SPLASH build system v0.1                                                                                             *
*                                                                                                                      *
* Copyright (c) 2013 Andrew D. Zonenberg                                                                               *
* All rights reserved.                                                                                                 *
*                                                                                                                      *
* Redistribution and use in source and binary forms, with or without modification, are permitted provided that the     *
* following conditions are met:                                                                                        *
*                                                                                                                      *
*    * Redistributions of source code must retain the above copyright notice, this list of conditions, and the         *
*      following disclaimer.                                                                                           *
*                                                                                                                      *
*    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the       *
*      following disclaimer in the documentation and/or other materials provided with the distribution.                *
*                                                                                                                      *
*    * Neither the name of the author nor the names of any contributors may be used to endorse or promote products     *
*      derived from this software without specific prior written permission.                                           *
*                                                                                                                      *
* THIS SOFTWARE IS PROVIDED BY THE AUTHORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED   *
* TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL *
* THE AUTHORS BE HELD LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES        *
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR       *
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT *
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE       *
* POSSIBILITY OF SUCH DAMAGE.                                                                                          *
*                                                                                                                      *
***********************************************************************************************************************/

#include "splashcore.h"

using namespace std;

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Construction / destruction

UnitTestNode::UnitTestNode(
	BuildGraph* graph,
	string command,
	string name,
	string partition)
	: BuildGraphNode(graph)
	, m_command(command)
	, m_name(name)
	, m_partition(partition)
{
	
}

UnitTestNode::~UnitTestNode()
{
	
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Testing

string UnitTestNode::GetOutputPath()
{
	//no actual output file
	return "";
}

string UnitTestNode::GetDescription()
{
	char desc[1024];
	snprintf(desc, sizeof(desc), "Unit test %s", m_name.c_str());
	return string(desc);
}

string UnitTestNode::GetBinaryPath()
{
	//no actual output file
	return "";
}

string UnitTestNode::GetHash()
{
	DebugPrintfHeading(5, "UnitTestNode::GetHash()\n");
	string hashin = "";
	
	//Update our dependencies
	UpdateDependencies();
	
	//Add data at this node
	hashin += sha256(m_name);
	hashin += sha256(m_command);
	
	//TODO: Hash the actual file we're going to execute if it's a script and not an executable
	
	//Add data for our dependencies
	for(size_t i=0; i<m_dependencies.size(); i++)
		hashin += m_dependencies[i]->GetHashCached(); 
	
	return sha256(hashin);
}

void UnitTestNode::Update(Cluster* cluster)
{
	string outdir   = m_graph->GetMetaDir() + "/" + GetHashCached();
	string okpath   = outdir  + "/build_successful";
	string failpath = outdir  + "/build_failed";
	
	//Add the default path to the search path
	string expath = CanonicalizePath(
		m_graph->GetMetaDir() + "/../" + CppToolchain::CreateDefaultToolchainCached()->GetArchitecture());
	
	DebugPrintfSilent(5, "    Re-test is necessary\n");
	
	//Rebuild our dependencies (in case any source files were auto-generated, etc)
	vector<ClusterJob*> deps;
	for(size_t i=0; i<m_dependencies.size(); i++)
	{
		BuildGraphNode* node = m_dependencies[i];
		node->UpdateCached(cluster);
		if(node->GetBuildJob() != NULL)
			deps.push_back(node->GetBuildJob());
	}
	
	//Print the heading
	DebugPrintfHeading(3, "Running unit test %s\n", m_name.c_str());
	DebugPrintfSilent (5, "    command %s\n", m_command.c_str());
	
	//Run the test case
	string batch_fname = outdir + "/test_" + m_name + ".sh";
	FILE* fp = fopen(batch_fname.c_str(), "w");
	if(!fp)
		FatalError("Failed to create batch script %s\n", batch_fname.c_str());
	fprintf(fp, "#!/bin/bash\n");
	fprintf(fp, "LD_LIBRARY_PATH=$LD_LIBRARY_PATH:%s\n", expath.c_str());
	fprintf(fp, "%s\n", m_command.c_str());
	fprintf(fp, "if [ $? -ne 0 ]; then\n");
	fprintf(fp, "    touch %s\n", failpath.c_str());
	fprintf(fp, "    exit 1\n");
	fprintf(fp, "else\n");
	fprintf(fp, "    touch %s\n", okpath.c_str());
	fprintf(fp, "fi\n");
	fclose(fp);
	if(0 != chmod(batch_fname.c_str(), 0755))
		FatalError("Failed to set execute permissions on batch script %s\n", batch_fname.c_str());
		
	//Submit the batch script
	m_job = cluster->SubmitBatchJob(batch_fname, m_partition, outdir, deps, 1, 512, m_features);
}

void UnitTestNode::UpdateDependencies()
{
	//no dependencies for a generic test
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Status checks

bool UnitTestNode::Passed()
{
	string okpath = m_graph->GetMetaDir() + "/" + GetHashCached() + "/build_successful";
	if(DoesFileExist(okpath))
		return true;
	return false;
}

////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
// Factory method

BuildGraphNode* UnitTestNode::CreateUnitTestNode(
	BuildGraph* graph,
	string command,
	string name,
	string partition)
{
	UnitTestNode* node = new UnitTestNode(graph, command, name, partition);
	graph->AddNode(node);
	graph->AddTest(node);
	return node;
}
